import React, { Component } from 'react';
import { InputNumber, Modal, Form, message, Radio, Upload } from "antd";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import TheQueryForm from '@/components/TheQueryForm';
import TheButton from "@/components/TheButton";
import TheSwitch from "@/components/TheSwitch";
import TheUpload from "@/components/TheUpload";
import TextArea from "antd/es/input/TextArea";
import { apiGetPage, apiAdd, apiDelete, apiUpdate, apiView } from "@/request/petCircleUtil/translation";

//提现申请
export default class WaitList extends Component {
  formRef = React.createRef()
  state = {
    editValue: "",
    dicType: 2,
    fileList: [],
    columns: [
      {
        title: "ID",
        dataIndex: "dictionaryId",
        key: "dictionaryId",
        width: 300
      },
      {
        title: "音频",
        dataIndex: "voiceUrl",
        key: "voiceUrl",
        width: 300,
        render: (text) => {
          return <audio src={text} controls />
        }
      },
      {
        title: "文本",
        dataIndex: "text",
        key: "text",
        width: 300
      },
      {
        title: '状态',
        dataIndex: 'isEnabled',
        key: 'isEnabled',
        render: (text, record) => {
          return <TheSwitch checked={!!text} onChange={() => this.setEnabled(!!!text, record.dictionaryId)} />
        }
      },
      {
        title: "添加时间",
        dataIndex: "createTime",
        key: "createTime",
      },
      {
        title: "排序",
        dataIndex: "sort",
        key: "sort",
      },
      {
        title: "操作",
        fixed: "right",
        width: 200,
        render: (text, record) => {
          return (
            <div>
              <TheButton haspermi={['petCircleUtil:translation:del']} onClick={() => this.del(record.dictionaryId)}>删除</TheButton>
              <TheButton haspermi={['petCircleUtil:translation:edit']} onClick={() => this.editShow(record)}>编辑</TheButton>
            </div>
          );
        },
      },
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    form_show: true,
    petType: "1",
    searchOption: [
      {
        field: 'text',
        label: '文本',
        placeholder: '请输入文本内容',
        required: false,
        type: 'Input',
        defaultValue: ''
      },
    ],
    options: [
      {
        label: '猫猫',
        value: '1'
      },
      {
        label: '狗狗',
        value: '2'
      },
    ],
    modalTitle: '',
    queryForm: {},
    type: '',
    passModalVisible: false,
  }

  componentDidMount = async () => {
    this.getData()
  }
  /**
  * @desc: 状态设置
  * @date: 2024-05-14
  * */
  setEnabled = (isEnabled, dictionaryId) => {
    apiUpdate({ isEnabled: ~~isEnabled, dictionaryId }).then(res => {
      if (res.code == 0 && res.data) {
        this.getData()
      }
    })
  }

  /**
   * @desc 获取列表
   * @data 
   * */
  getData = async () => {
    const params = {
      ...this.state.pageData,
      ...this.state.queryForm,
      dicType: this.state.dicType,
      petType: this.state.petType
    }
    apiGetPage({ ...params }).then(res => {
      if (res.code === 0 && res.data) {
        this.setState({
          dataSource: res.data,
          pageData: {
            pageNo: res.pageNo,
            pageSize: res.pageSize
          },
          total: res.totalCount,
        })
      }
    })
  }
  /**
   * @desc 表格组件分页切换
   * @params number|string {pageNo} 页号
   * @params number|string {pageSize} 每页条数
   * */
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => {
      this.getData()
    })
  };
  /**
   * @desc 表格搜索组件重置搜索条件
   * */
  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }
  /**
   * @desc 表格搜索组件搜索
   * */
  onFormSearch(value) {
    let { queryForm } = this.state;
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 },
      queryForm: { ...value }
    }, () => {
      this.getData()
    })
  }
  /**
   * @desc 删除
   * */
  del = (dictionaryId) => {
    React.$confirm({
      title: "确认删除该词条吗",
      onOk: async () => {
        apiDelete({ dictionaryId }).then(res => {
          React.$message({
            type: 'success',
            content: '删除成功',
          })
          this.setState({
            pageNo: 1,
          }, () => {
            this.getData()
          })
        })
      },
    });
  }
  editShow = async (value) => {
    let type = ""
    this.state.options.some(item => {
      if (item.value == this.state.petType) {
        type = item.label
      }
      return item.value == this.state.petType
    })

    this.setState({
      passModalVisible: true, modalTitle: '编辑日常词条', type, editValue: value, fileList: [{
        uid: new Date().getTime(),
        name: "音频",
        status: "done",
        url: value.voiceUrl,
      },]
    }, () => {
      this.formRef.setFieldValue('text', value.text)
      this.formRef.setFieldValue('voiceUrl', value.voiceUrl)
      this.formRef.setFieldValue('sort', value.sort)
    })
  }
  addShow = async () => {
    let type = ""
    this.state.options.some(item => {
      if (item.value == this.state.petType) {
        type = item.label
      }
      return item.value == this.state.petType
    })
    this.setState({ passModalVisible: true, modalTitle: '新增日常词条', type })
  }
  /**
   * @desc 开启驳回modal
   * */
  goReject = (values) => {
    this.setState({
      rejectModalVisible: true,
      withdrawalRecordId: values.withdrawalRecordId
    })
  }

  handleSizeChange = (e) => {
    this.setState({
      petType: e.target.value,
      pageData: {
        pageNo: 1,
        pageSize: 10,
      },
    }, () => {
      this.getData()
    })
  };
  onCancel = () => {
    this.formRef.resetFields()
    this.setState({ passModalVisible: false,fileList:[]})
  }

  passModalOk = () => {
    const add = () => {
      const { petType, dicType } = this.state
      // 驳回提现申请
      this.formRef.validateFields().then(async (values) => {
        let res = await apiAdd({
          ...values,
          dicType,
          petType,
        })
        if (res.code === 0) {
          message.success('添加成功')
          this.setState({ passModalVisible: false })
          this.formRef.resetFields()
          this.pageChange(1, 10)
        }
      })
    }
    const edit = () => {
      const { petType, dicType, editValue } = this.state
      // 驳回提现申请
      this.formRef.validateFields().then(async (values) => {
        let res = await apiUpdate({
          ...values,
          dicType,
          petType,
          dictionaryId: editValue.dictionaryId
        })
        if (res.code === 0) {
          message.success('修改成功')
          this.setState({ passModalVisible: false })
          this.formRef.resetFields()
          this.pageChange(1, 10)
        }
      })
    }
    switch (this.state.modalTitle) {
      case "编辑日常词条":
        edit()
        break;
      case "新增日常词条":
        add()
        break;
    }

    this.setState({ rejectLoading: false })
  }
  getFileResult = (value, key) => {
    if (value.length > 0 && value[0].hasOwnProperty('response') && value[0].response) {
      this.formRef.setFieldsValue({
        [key]: value[0].response.data
      })
    } else {
      this.formRef.setFieldsValue({
        [key]: ''
      })
    }
  };
  // 图片上传回调
  getDetailsFileResult = value => {

    if (value && value.length) {
      let arr = value.map(v => {
        // console.log(v)
        if (v.response && v.response.code === 0) {
          return v.response.data
        } else {
          return v.url
        }
      }).join(',')
      this.formRef.setFieldsValue({
        voiceUrl: arr
      })
    } else {
      this.formRef.setFieldsValue({
        voiceUrl: ''
      })
    }
  }
  render() {
    let {
      type,
      petType,
      passModalVisible,
      columns,
      dataSource,
      pageData: { pageNo, pageSize },
      total,
      searchOption,
      form_show,
      passLoading,
      modalTitle,
      options,
      fileList
    } = this.state;
    return (
      <div className={"p-layout-box commodity-content"}>
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >
          <TheButton haspermi={['petCircleUtil:translation:add']} type={'default'} size="middle" onClick={this.addShow}>新增</TheButton>
        </TheQueryForm>
        <Radio.Group value={petType} options={options} optionType="button" onChange={this.handleSizeChange} style={{ marginBottom: '20px' }} />
        <TheTable
          scroll={{ x: '960', y: '63vh' }}
          columns={columns}
          dataSource={dataSource}
          rowKey={'withdrawalRecordId'}
        />
        <ThePagination
          pageNo={pageNo}
          pageSize={pageSize}
          total={total}
          pageChange={this.pageChange}
        />
        <Modal
          title={modalTitle}
          open={passModalVisible}
          onOk={this.passModalOk}
          maskClosable={false}
          confirmLoading={passLoading}
          onCancel={() => this.onCancel()}
        >
          <Form
            labelCol={{
              span: 4,
            }}
            wrapperCol={{
              span: 19,
            }}
            layout="horizontal"
            ref={(ref) => this.formRef = ref}
          >

            <Form.Item label="宠物类型" name={"type"} >
              {type}
            </Form.Item>
            <Form.Item label="上传音频" name={"voiceUrl"} rules={[{ required: true }]}>
              <TheUpload accept={['audio/x-m4a', 'audio/mpeg']} len={1} fileType="audio" maxSize={10} fileList={fileList} getFileResult={this.getDetailsFileResult} isConversion={false} />
            </Form.Item>
            <Form.Item label="文本内容" name={"text"} rules={[{ required: true }]}>
              <TextArea rows={4}  maxLength={5} showCount allowClear />
            </Form.Item>
            <Form.Item label="排序" name={"sort"} >
              <InputNumber precision={0} min={1} max={999} maxLength={3} />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }
}
